package com.rich.service.impl;

import java.util.List;

import com.rich.dao.OrderDao;
import com.rich.domain.Order;
import com.rich.domain.OrderItem;
import com.rich.domain.PageBean;
import com.rich.service.OrderService;
import com.rich.utils.BeanFactory;
import com.rich.utils.DataSourceUtils;

public class OrderServiceImpl implements OrderService{

	OrderDao od = (OrderDao) BeanFactory.getBean("OrderDao");
	/**
	 * 保存订单
	 */
	@Override
	public void save(Order order) throws Exception {
		try {
			//开启事务
			DataSourceUtils.startTransaction();
			//向orders表中插入一个订单数据
			od.saveOrder(order);
			//向orderitem表中插入多条订单项数据
			for (OrderItem oi : order.getItems()) {
				od.saveOrderItem(oi);
			}
			
			//事务控制
			DataSourceUtils.commitAndClose();
		} catch (Exception e) {
			System.out.println("事务回滚");
			DataSourceUtils.rollbackAndClose();
		}
	}
	
	/**
	 * 我的订单
	 */
	@Override
	public PageBean<Order> findMyOrderByPage(int pageNumber, int pageSize, String uid) throws Exception {
		// 创建pageBean
		PageBean<Order> pb = new PageBean<>(pageNumber, pageSize);
		//查询总条数，设置总条数
		int totalRecore = od.getTotalRecore(uid);
		pb.setTotalRecore(totalRecore);
		//查询当前页数据，设置当前页数据
		List<Order> data = od.findMyOrderByPage(pb,uid);
		pb.setData(data);
		return pb;
	}

	/**
	 * 获取单个订单的详情
	 */
	@Override
	public Order getById(String oid) throws Exception {
		return od.getById(oid);
	}

	/**
	 * 修改订单信息
	 */
	@Override
	public void update(Order order) throws Exception {

		od.update(order);
	}

	/**
	 * 根据状态获取表单列表
	 */
	@Override
	public List<Order> findAllByState(String state) throws Exception {
		return od.findAllByState(state);
	}

}
